package com.chen.positioning.mypositioning.controller;

import com.chen.positioning.mypositioning.entity.Mypositioning;
import com.chen.positioning.mypositioning.service.MypositioningService;
import com.chen.positioning.user.entity.UserManagement;
import com.chen.positioning.user.service.UserManagementService;
import com.chen.positioning.util.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户信息 Controller
 *
 * @author halo
 * @create 2019-07-20 17:09
 */
@Controller
@RequestMapping("/mypositioning")
public class MypositioningController {
    @Autowired
    private UserManagementService userManagementService;
    @Autowired
    private MypositioningService mypositioningService;
    @Autowired
    CommonJsonReturnMessage commonJsonReturnMessage;
    @Autowired
    Base64Util base64Util;
    @Autowired
    WsdlUtil wsdlUtil;
    @Autowired
    RandomNumber randomNumber;
    @Autowired
    LatitudeAndLongitudeUtil latitudeAndLongitudeUtil;

    private static final Logger logger = LoggerFactory.getLogger(MypositioningController.class);

    private double PAYMENT_AMOUNT = 88;

    /**
     * 手机定位初始页面
     *
     * @return
     */
    @RequestMapping(value = "/phonePositioning", method = {RequestMethod.POST, RequestMethod.GET})
    public String phonePositioning() {
        logger.info("已进入手机定位初始页面....");
        return "/inputPositioning";
    }

    /**
     * 根据手机号展示其定位
     *
     * @param mypositioningPhoneNumber
     * @param mypositioningName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/viewMap", method = {RequestMethod.POST, RequestMethod.GET})
    public String viewMap(HttpSession session, HttpServletResponse response,
                          String mypositioningPhoneNumber, String mypositioningName) {
        try {
            logger.info("viewMap,mypositioningPhoneNumber:" + mypositioningPhoneNumber + "mypositioningName:" + mypositioningName);
            UserManagement userManagement = (UserManagement) session.getAttribute("userManagement");
            //判断session不为空没有超时,否则要重新登录
            if (null != userManagement && 0 != userManagement.getUserId() && null != userManagement.getUserId()) {
                //根据用户Id实时查询用户余额是否够,如不够需要跳支付宝界面
                UserManagement userManagement2 =
                        userManagementService.findAllUserManagementInfo(userManagement.getUserId());
                if (userManagement2.getBalance() >= PAYMENT_AMOUNT) {
                    //余额足够,直接走定位流程
                    if (StringUtils.isNotEmpty(mypositioningPhoneNumber)) {
                        List<String> list = wsdlUtil.returnAttributionForPhonenum(mypositioningPhoneNumber);//返回省会和城市信息
                        logger.info("返回省会和城市信息 viewMap  list["+list.toString()+"]");
                        if (null != list && list.size() > 1 && StringUtils.isNotEmpty(list.get(0)) && StringUtils.isNotEmpty(list.get(1))) {
                            logger.info("返回省会和城市信息 == list[" + list.toString() + "]");
                            //广东 深圳
                            List<String> list2 = latitudeAndLongitudeUtil.getLatitudeAndLongitude(list.get(0),
                                    list.get(1));//根据城市信息获取到其经度纬度
                            if (null != list2 && list2.size() > 0 && StringUtils.isNotEmpty(list2.get(0)) && StringUtils.isNotEmpty(list2.get(1))) {
                                logger.info("viewMap==== 得到的经纬度为 :" + list2.get(0) + list2.get(1));
                                List<String> newList= new ArrayList<String>();
                                newList=randomNumber.generation(list2);
                                logger.info("随机改变过后的 newList["+newList.toString()+"]");

                                if(null != newList && newList.size() > 0
                                        && StringUtils.isNotEmpty(newList.get(0))
                                        && StringUtils.isNotEmpty(newList.get(1))){

                                    //组装Mypositioning信息,把此次定位记录插入到我的定位表中
                                    Mypositioning mypositioning = new Mypositioning();

                                    mypositioning.setMypositioningPhoneNumber(mypositioningPhoneNumber);
                                    mypositioning.setMypositioningCity(list.get(0));
                                    mypositioning.setUserId(userManagement2.getUserId());
                                    mypositioning.setMypositioningName(mypositioningName);
                                    mypositioning.setMypositioningAddress(list.get(1));
                                    mypositioning.setLongitude(newList.get(0));
                                    mypositioning.setLongitude(newList.get(1));

                                    mypositioningService.addMypositioningInfo(mypositioning);//添加定位信息

                                    //判断是否为VIP 以及 包月时间是否到期
                                    if (userManagement2.getVipFlag() != 1) {
                                        Date day = new Date();
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        Date nowDay = dateFormat.parse(df.format(day));
                                        Date dataBaseTime =
                                                dateFormat.parse(df.format(userManagement2.getVipMaturityDate()));
                                        logger.info("包月到期时间为[" + dataBaseTime + "]当前的时间为[" + nowDay + "]");
                                        //nowDay 等于 dataBaseTime，则返回值 0； nowDay 在 dataBaseTime 参数之前，则返回小于 0 的值；
                                        // 如果此 nowDay 在 dataBaseTime 参数之后，则返回大于 0 的值
                                        int i = nowDay.compareTo(dataBaseTime);
                                        if (nowDay.compareTo(dataBaseTime) > 0) {
                                            //使用完定位服务后扣除其余额(包月期间不扣除)
                                            logger.info("扣钱了。。。。。。。。。。");
                                            userManagementService.updateBalanceByUserId(userManagement2.getUserId(),PAYMENT_AMOUNT);
                                        }
                                    }
                                    session.setAttribute("userManagement", userManagement2);
                                    String returnUrl =
                                            "https://restapi.amap.com/v3/staticmap?location=" + newList.get(0) + "," + newList.get(1) + "&zoom=15&size=550*600&markers=mid,,A:" + newList.get(0) + "," + newList.get(1) + "&scale=2&key=61f70e4c4146cb3131cfca7493365692";
                                    logger.info("returnUrl======" + returnUrl);
                                    return commonJsonReturnMessage.successReturn("地图展示成功", returnUrl);

                                }else{
                                    logger.info("随机经纬度生成失败。。。");
                                    return commonJsonReturnMessage.failReturn("您输入的手机号码无法查询到经纬度信息", "您输入的手机号码无法查询到经纬度信息");
                                }
                            } else {
                                return commonJsonReturnMessage.failReturn("您输入的手机号码无法查询到经纬度信息", "您输入的手机号码无法查询到经纬度信息");
                            }
                        } else {
                            return commonJsonReturnMessage.failReturn("您输入的手机号码无法查询到归属地位置", "您输入的手机号码无法查询到归属地位置");
                        }

                    } else {
                        return commonJsonReturnMessage.failReturn("手机号码不能为空", "手机号码不能为空");
                    }
                } else {
                    //如余额不足,需要走支付宝充值流程
                    return commonJsonReturnMessage.failReturn("余额不足请充值", "/rechargeRecord/recharge_monthly");
                }
            } else {
                return commonJsonReturnMessage.failReturn("登录超时请重新登录", "/userManagement/loginIndex");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("viewMap error:" + e);
            return commonJsonReturnMessage.failReturn("地图展示失败", e);
        }
    }

    /**
     * 查询我的定位记录
     *
     * @param session
     * @param response
     * @return
     */
    @RequestMapping(value = "/findAllMypositioning", method = {RequestMethod.POST, RequestMethod.GET})
//    @ResponseBody
    public String findAllMypositioning(HttpSession session, HttpServletResponse response, Model model) {

        UserManagement userManagement= (UserManagement) session.getAttribute("userManagement");
        try {
            if (null!=userManagement && 0<userManagement.getUserId()){
                logger.info("findAllMypositioning,userId:" + userManagement.getUserId());
                List<Mypositioning> mypositioningList = mypositioningService.findAllMypositioning(userManagement.getUserId());
                logger.info("mypositioningList  ["+mypositioningList.toString()+"]");
                session.setAttribute("mypositioningList",mypositioningList);
                model.addAttribute("mypositioningList",mypositioningList);
                return "/mypositioning";
            }else{
                logger.info("session过期,请重新登录");
                return "/login";
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询定位记录失败 出现异常:", e);
            return commonJsonReturnMessage.failReturn("查询定位记录失败", e);
        }
    }
}
